package com.yuexunit.finance.system.action.v1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Singleton;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.web.annotation.ActionServlet;

/**
 *@version 创建时间：2017年7月10日 下午10:32:09
 *@author wenwenlong
 *类说明
 */

@ActionServlet({"/api/[^/]+/viewPdfFile.json"})
@Singleton
public class ViewPdfFileAction extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		TransferService fileService = ComponentFactory.loadClass(TransferService.class);

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		String fileUuid = request.getParameter("fileUuid");
		FileEntry fe = fileService.inquireFileEntry(fileUuid);
		String filePath = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe.getUri();
		Path path = Paths.get(filePath);
		String contentType = Files.probeContentType(path);
		
		//设置响应内容类型为PDF类型 
        response.setContentType(contentType + ";charset=utf-8");
          
        ServletOutputStream sos = response.getOutputStream();  
          
        //不在网页中打开，而是直接下载该文件
        //response.setHeader("Content-disposition", "attachment;filename="+fe.getFileName());  
        response.addHeader("Content-Disposition", "inline;filename="+new String(fe.getFileName().getBytes("GB2312"), "ISO_8859_1"));
          
        File pdf = null;  
        FileInputStream fis = null;  
        byte[] buffer = new byte[1024*1024];  
        pdf = new File(filePath);  
        response.setContentLength((int) pdf.length());  
        fis = new FileInputStream(pdf);  
        while((fis.read(buffer, 0, 1024*1024)) != -1){  
            sos.write(buffer, 0, 1024*1024);  
        }  
        sos.close();  
        fis.close();   
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
